package com.atguigu.gmall.realtime.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/19 9:20
 */
public class MyJDBCUtil {
    public static Connection getConnection(String url) {
        // ....?username=xx&password=xxx
        try {
            return DriverManager.getConnection(url);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static <T> List<T> queryList(Connection conn,
                                        String sql,   //  select * from dim_user_info where id=?
                                        Object[] args,  // 给sql中的占位符赋值
                                        Class<T> clazz,
                                        boolean underscoreTToCamel) {
        
        try (PreparedStatement ps = conn.prepareStatement(sql)) { // 1.7 功能, 这个地方打开的资源, 会自动关闭
            // 1. 给sql中的占位符赋值
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            // 2. 执行sql, 获取结果
            final ResultSet resultSet = ps.executeQuery();
            // 3. 从结果集中得到元数据信息
            final ResultSetMetaData metaData = resultSet.getMetaData();
            // 4. 遍历结果集中的每一行数据, 每一行封装到一个T类型中
            final ArrayList<T> result = new ArrayList<>();
            while (resultSet.next()) {
                T t = clazz.newInstance();  // 通过反射的方式创建对象  new T()
                // 5.1 遍历每一列, 把一行内的所有列封装到一个T对象中
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    if (underscoreTToCamel) { // 下划线改成驼峰  user_name  userName
                        columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                    }
                    final Object columnValue = resultSet.getObject(i + 1);
                    
                    BeanUtils.setProperty(t, columnName, columnValue);
                }
                // 4.2 把对象添加到要返回的集合中
                result.add(t);
            }
            return result;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void main(String[] args) {
        String phoenixUrl = "jdbc:phoenix:hadoop162,hadoop163,hadoop164:2181";
        final Connection conn = getConnection(phoenixUrl);
        final String sql = "select * from DIM_SKU_INFO where id=?";
        Object[] arg = {"1"};
        final List<HashMap> result = queryList(conn, sql, arg, HashMap.class, false);
        System.out.println(result.get(0));
    }
}
